package gui.panels;

import com.google.common.eventbus.Subscribe;
import eventbus.events.AddTrafficEvent;
import gui.SubPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class FlowMonitoringSubPanel extends SubPanel {
    private static final String CHART_TITLE = "流量实时监控";
    private static final String X_TITLE = "时间/(s)";
    private static final String Y_TITLE = "消息处理量/(次)";
    private static final String X_DESC = "消息";

    AtomicLong count = new AtomicLong();
    TimeSeries series = new TimeSeries(X_DESC);

    public FlowMonitoringSubPanel() {
        ChartPanel chartPanel = createChart();
        chartPanel.setLocation(100, 75);
        this.add(chartPanel);
        ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
        //开启流量监控，每1s刷新一次
        pool.scheduleAtFixedRate(() -> {
            series.add(new Millisecond(), count.get());
            count.set(0);
        }, 0, 1, TimeUnit.SECONDS);
    }

    public ChartPanel createChart() {
        JFreeChart chart = ChartFactory.createTimeSeriesChart(CHART_TITLE,
                X_TITLE,
                Y_TITLE,
                new TimeSeriesCollection(this.series),
                true, true, false);


        XYPlot xyplot = chart.getXYPlot();
        DateAxis dateaxis = (DateAxis) xyplot.getDomainAxis();
        dateaxis.setAutoRange(true);
        dateaxis.setFixedAutoRange(20 * 1000.0); // 20 seconds
        dateaxis.setVerticalTickLabels(true);


        //顶部
        chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 20));//设置标题字体
        //左侧
        ValueAxis rangeAxis = xyplot.getRangeAxis();//获取柱状
        rangeAxis.setRange(0.0, 50.0);//设置上下限
        rangeAxis.setLabelFont(new Font("黑体", Font.BOLD, 15));
        //底部
        dateaxis.setDateFormatOverride(new SimpleDateFormat("MM-dd HH:mm:ss"));
        dateaxis.setLabelFont(new Font("黑体", Font.BOLD, 14));     //水平底部标题
        dateaxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12)); //垂直标题

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setSize(800, 450);
        return chartPanel;
    }

    @Subscribe
    public void addTraffic(AddTrafficEvent e) {
        count.incrementAndGet();
    }
}
